package chapter8;

import java.util.Scanner;

/**
 * 顺时针旋转矩阵90°
 */
public class RotateMatrix {
    public static void rotate(int[][] matrix) {
        int tR = 0;
        int tC = 0;
        int dR = matrix.length - 1;
        int dC = matrix[0].length - 1;
        while (tR < dR) {
            rotateEdge(matrix, tR++, tC++, dR--, dC--);
        }
    }

    private static void rotateEdge(int[][] m, int tR, int tC, int dR, int dC) {
        int times = dC - tC; // 总的组数,M*M,就是M-1组
        int tmp = 0;
        for (int i = 0; i != times; ++i) { //一次循环，就是一组占据调整
            tmp = m[tR][tC + i];
            m[tR][tC + i] = m[dR - i][tC];
            m[dR - i][tC] = m[dR][dC - i];
            m[dR][dC - i] = m[tR + i][dC];
            m[tR + i][dC] = tmp;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        rotate(matrix);
        for (int i = 0; i < matrix.length; ++i) {
            for (int j = 0; j < matrix[0].length; ++j) {
                if (j == matrix[0].length - 1) {
                    System.out.print(matrix[i][j]);
                    break;
                }
                System.out.print(matrix[i][j] + " ");
            }
            if (i < matrix.length - 1) {
                System.out.println();
            }
        }
    }
}
